<?php
/**
 * country.php
 *
 * Created on 2014-12-8
 * Create by LDD
 */
namespace haibao\www\data;
use \haibao\www\model\filter\FeaturePublish as FeaturePublishFilter;
use \haibao\frame\data\query\Condition as Condition;
use haibao\www\model\data\SnsanyTopic as SnsanyTopicModel;
use haibao\www\model\data\ZtSpecial as ZtSpecialModel;
use haibao\www\model\data\ZtLog as ZtLogModel;
use haibao\www\model\filter\User as UserFilter;
use haibao\www\web\view\utility\Feature as FeatureUtility;
use haibao\www\web\view\utility\File as FileUtility;
use haibao\www\model\filter\SnsAnyTopic as SnsAnyTopicFilter;
use haibao\www\model\filter\ZtSpecial as ZtSpecialFilter;
use haibao\www\data\ZtSpecial as ZtSpecialData;
use haibao\www\model\data\FeaturePublish as FeaturePublishModel;
use haibao\www\model\data\FeatureIni as FeatureIniModel;

class FeaturePublish extends \haibao\www\data\BaseMysql{
	private static $mongoDb = null;
	
	public function __construct(){
		parent::__construct('\haibao\www\model\data\FeaturePublish');
	}
	
	public function addFeatureRecord($itemModels,$featureId,$defineId){
		$this->beginTranscation();
		
		try{
			if (!$defineId){
				$model = new \haibao\cms\model\data\FeatureRecordDefine();
				$model->CreateTime = new \DateTime();
				$model->FeatureId = $featureId;
				$this->add($model);
				$defineId = $model->Id;
			}
			
			foreach ($itemModels as $itemModel){
				$itemModel->DefineId = $defineId;
			}
			$this->addAll($itemModels);
		}
		catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		
		$this->endTranscation();
		
		return $defineId;
	}
	
	public function updateFeatureIni($featureId,$id,$arrSet){
		//兼容旧数据
		if (!$id){
			$sql = 'select Id from FeatureIni where FeatureId=%s';
			$result = $this->query($sql,array($featureId));
			if ($result && ($row = $result->fetch_assoc())){
				$id = $row['Id'];
			}
			else{
				$model = new FeatureIniModel();
				$model->FeatureId = $featureId;
				$this->add($model);
				$id = $model->Id;
			}
		}
		
		$this->setModelName('\haibao\cms\model\data\FeatureIni');
		$this->updateById($id, $arrSet);
		$this->setModelName('\haibao\cms\model\data\FeaturePublish');
	}
	
	public function updateFeatureParamById($id,$arrSet){
		if ($id){
			$this->setModelName('\haibao\cms\model\data\FeatureParam');
			$this->updateById($id, $arrSet);
			$this->setModelName('\haibao\cms\model\data\FeaturePublish');
		}
	}
	
	public function addDynamicDefine($model){
		$this->beginTranscation();
		
		try{
			$this->add($model);
			foreach ($model->Items as $item){
				$item->DefineId = $model->Id;
			}
			$this->addAll($model->Items);
		}
		catch (\Excpetion $e){
			$this->rollback();
			throw $e;
		}
		
		$this->endTranscation();
	}
	
	public function updateDynamicDefine($model){
		$this->beginTranscation();
		
		try{
			$arrSet = array(
				\haibao\cms\model\filter\FeatureDynamicDefine::CONDITION_FIELD_NAME_CODE=>$model->Code,
				\haibao\cms\model\filter\FeatureDynamicDefine::CONDITION_FIELD_NAME_NAME=>$model->Name
			);
			$this->setModelName('\haibao\cms\model\data\FeatureDynamicDefine');
			$this->updateById($model->Id, $arrSet);
			
			$sql = 'delete from FeatureDynamicItem where DefineId=%s';
			$this->query($sql,array($model->Id));
			
			$this->addAll($model->Items);
			$this->setModelName('\haibao\cms\model\data\FeaturePublish');
		}
		catch (\Excpetion $e){
			$this->rollback();
			throw $e;
		}
		
		$this->endTranscation();
	}
	
	public function delDynamicDefine($defineId){
		$this->beginTranscation();
		
		try{
			$sql = 'delete from FeatureDynamicDefine where id=%s';
			$this->query($sql,array($defineId));
			$sql = 'delete from FeatureDynamicItem where DefineId=%s';
			$this->query($sql,array($defineId));
		}
		catch (\Excpetion $e){
			$this->rollback();
			throw $e;
		}
		
		$this->endTranscation();
	}
	
	public function delParamById($paramId){
		$sql = 'delete from FeatureParam where id=%s';
		$this->query($sql,array($paramId));
	}
	
	public function updateFeatureParam($id,$arrSet){
		if ($id){
			$this->setModelName('\haibao\cms\model\data\FeatureParam');
			$this->updateById($id, $arrSet);
			$this->setModelName('\haibao\cms\model\data\FeaturePublish');
		}
	}
	
	public function addFeatureIni($model){
		$this->beginTranscation();
		
		try{
			$sql = 'delete from FeatureIni where FeatureId=%s';
			$this->query($sql,array($model->FeatureId));
			$this->add($model);
		}
		catch (\Exception $e){
			$this->rollBack();
			throw $e;
		}
		
		$this->endTranscation();
	}
	
	/**
	 * 修改专题显示状态
	 */
	public function listFeature($featureId,$isList){
		if ($oldFeatureId = $this->getDataMigration(new FeaturePublishModel(), $featureId)){
			$arrSet = array(
				FeaturePublishFilter::CONDITION_FIELD_NAME_IS_LIST=>$isList
			);
			
			if ($isList == FeaturePublishModel::IS_LIST_ENABLE){
				$oldArrSet = array(
						ZtSpecialFilter::CONDITION_FIELD_NAME_LIST_SHOW=>ZtSpecialModel::LIST_SHOW_ENABLE,
						ZtSpecialFilter::CONDITION_FIELD_NAME_STATUS=>ZtSpecialModel::STATUS_ENABLE,
				);
			}else{
				$oldArrSet = array(
						ZtSpecialFilter::CONDITION_FIELD_NAME_LIST_SHOW=>ZtSpecialModel::LIST_SHOW_DISABLE,
				);
			}
			
			$ztData = new ZtSpecialData();
			
			$this->beginTranscation();
			try {
				$this->updateById($featureId, $arrSet);
				$ztData->setModelName('\haibao\cms\model\data\ZtSpecial');
				$ztData->updateById($oldFeatureId, $oldArrSet);
			}
			catch (\Exception $e){
				$this->rollback();
				throw $e;
			}
			
			$this->endTranscation();
		}
	}
	
	public function getDynamicList($featureId,$parameters){
		$data = array();
		if ($parameters){
			
			//循环查询，获取每个分类的总数及分页记录
			foreach ($parameters as $parameter){
				$groupCode = $parameter['code'];
				$currentPage = $parameter['currentPage'];
				$pageSize = $parameter['pageSize'];
				$resultCount = 0;
	
				$countSql = ' select count(*) as num from FeatureItemGroupData a1';
				$countSql .= ' inner join FeatureGroupDefine a2 on a1.GroupDefineId = a2.Id';
				$countSql .= ' where a2.FeatureId=%s and a2.GroupCode=%s';
				
				$result = $this->query($countSql,array($featureId,$groupCode));
				if ($result && ($row = $result->fetch_assoc())){
					$resultCount = $row['num'];
				}
				
				if ($resultCount > 0){
					$innerSql = ' select a1.Id from FeatureItemGroupData a1';
					$innerSql .= ' inner join FeatureGroupDefine a2 on a1.GroupDefineId = a2.Id';
					$innerSql .= ' where a2.FeatureId=%s';
					$innerSql .= ' and a2.GroupCode=%s';
					$innerSql .= ' order by a1.CreateTime desc limit %s,%s';
						
					$searchSql = 'select a2.GroupCode,a1.ShowTime,a1.CreateTime,a4.ItemCode,a4.ItemType,a3.ItemValue,a1.Id,a4.Id as ItemId from FeatureItemGroupData a1';
					$searchSql .= ' inner join FeatureGroupDefine a2 on a1.GroupDefineId = a2.Id';
					$searchSql .= ' inner join FeatureGroupDefineItemData a3 on a1.Id= a3.ItemGroupDataId';
					$searchSql .= ' inner join FeatureGroupDefineItem a4 on a3.GroupDefineItemId = a4.Id';
					$searchSql .= ' inner join ('.$innerSql.') s on s.Id = a1.Id';
	
					if ($result = $this->query($searchSql,array($featureId,$groupCode,(($currentPage-1)*$pageSize),$pageSize))){
						while ($row = $result->fetch_assoc()){
							$groupCode = $row['GroupCode'];
							$id = $row['Id'];
							$itemId = $row['ItemId'];
	
							if (!isset($data[$groupCode])){
								$data[$groupCode] = array(
										'currentPage'=>$currentPage,
										'pageSize'=>$pageSize,
										'rowCount'=>$resultCount,
										'pageCount'=>ceil($resultCount/$pageSize),
										'data'=>array()
								);
							}
	
							if (!isset($data[$groupCode]['data'][$id])){
								$data[$groupCode]['data'][$id] = array();
								$data[$groupCode]['data'][$id]['id'] = $id;
								$data[$groupCode]['data'][$id]['createTime'] = $row['CreateTime'];
								$data[$groupCode]['data'][$id]['showTime'] = $row['ShowTime'];
							}
							
							$data[$groupCode]['data'][$id][$row['ItemCode']] = $row['ItemValue'];
						}
					}
					
					$data[$groupCode]['data'] = array_values($data[$groupCode]['data']);
				}
			}
		}
		
		return $data;
	}
	
	public function delDynamic($itemGroupId){
		if ($itemGroupId){
			$this->beginTranscation();
			try{
				$sql = 'delete from FeatureItemGroupData where Id=%s';
				$this->query($sql,array($itemGroupId));
				$sql = 'delete from FeatureGroupDefineItemData where ItemGroupDataId=%s';
				$this->query($sql,array($itemGroupId));
			}
			catch (\Exception $e){
				$this->rollback();
				throw $e;
			}
			$this->endTranscation();
		}
	}
	
	public function updateFeatureDynamic($itemDataModels,$itemGroupId,$showTime){
		$ids = array();
		foreach ($itemDataModels as $itemDataModel){
			array_push($ids,$itemDataModel->Id);
			$itemDataModel->Id = null;
		}
		
		$this->beginTranscation();
		try{
			$sql = 'delete from FeatureGroupDefineItemData where id in ('.implode(',',$ids).')';
			$this->query($sql);
			$this->addAll($itemDataModels);
			
			if (!$showTime){
				$showTime = new \DateTime();
			}
			$sql = 'update FeatureItemGroupData set ShowTime=%s where id=%s';
			$this->query($sql,array($showTime,$itemGroupId));
		}
		catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function vote($id,$name){
		$count = 0;
		$sql = 'select * from FeatureVote where FeatureId=%s and VoteName=%s';
		$result = $this->query($sql,array($id,$name));
		
		if ($row = $result->fetch_assoc()){
			$sql = 'update FeatureVote set Count=Count+1 where FeatureId=%s and VoteName=%s';
			$this->query($sql,array($id,$name));
			$count = $row['Count'] + 1;
		}else{
			$sql = 'insert into FeatureVote(FeatureId,VoteName,Count) values(%s,%s,1)';
			$this->query($sql,array($id,$name));
			$count = 1;
		}
		
		return $count;
	}
	
	public function updateOldFeatureRecord($featureModel,$oldFeature){
		$author = '';
		$picName = '';
		$userData = new \haibao\cms\data\User();
		$userModel = $userData->getUserById($featureModel->CreateBy);
		if ($userModel){
			$author = $userModel->UserName;
		}
		$ztArrSet = array(
			ZtSpecialFilter::CONDITION_FIELD_NAME_UPDATE_DATE=>$featureModel->UpdateTime,
			ZtSpecialFilter::CONDITION_FIELD_NAME_URL=>$featureModel->Url,
			ZtSpecialFilter::CONDITION_FIELD_NAME_LIST_DATE=>$featureModel->ListTime,
		);
		$snsArrSet = array(
			SnsAnyTopicFilter::CONDITION_FIELD_NAME_DESC=>str_replace('_海报时尚网','',$featureModel->FeatureName),
			SnsAnyTopicFilter::CONDITION_FIELD_NAME_URL=>$featureModel->Url
		);
		
		$ztLogModel = new ZtLogModel();
		$ztLogModel->UserId = $author;
		$ztLogModel->Content = '编辑专题';
		$ztLogModel->AddTime = date('Y-m-d H:i:s');
		
		$ztData = new ZtSpecialData();
		$oldFeature = $ztData->getOneById($oldFeature->Id);
		
		try {
			$ztData->beginTranscation();
				
			$ztData->setModelName('\haibao\cms\model\data\ZtSpecial');
			$ztData->updateById($oldFeature->Id, $ztArrSet);
			
			$ztData->setModelName('\haibao\cms\model\data\SnsAnyTopic');
			$ztData->updateById($oldFeature->SnsTid,$snsArrSet);
				
			$ztLogModel->ZtsId = $oldFeature->Id;
			$ztData->add($ztLogModel);
			$ztData->setModelName('\haibao\cms\model\data\ZtSpecial');
			
			$ztData->endTranscation();
		}
		catch (\Exception $e){
			$ztData->rollback();
			throw $e;
		}
	}
	
	/**
	 * 同步专题记录到旧数据库
	 * @param \haibao\cms\model\data\FeaturePublish $featureModel
	 */
	public function saveOldFeatureRecord($featureModel){
		$id = null;
		$author = '';
		$picName = '';
		$userData = new \haibao\cms\data\User();
		$userModel = $userData->getUserById($featureModel->CreateBy);
		if ($userModel){
			$author = $userModel->UserName;
		}
		
		//保存图片到旧专题地址
		if ($featureModel->PictureId){
			$imageData = new \haibao\cms\data\ImageLibrary();
			$image = $imageData->getImgageByMongo($featureModel->PictureId);
			$imageContent = $image->getBytes();
			$picName = FeatureUtility::saveOldFeatureImage($image->file['Filename'], $imageContent);
		}
		
		$snsModel = new SnsanyTopicModel();
		$ztModel = new ZtSpecialModel();
		$ztLogModel = new ZtLogModel();
		
		$snsModel->Url = $featureModel->Url;
		$snsModel->Desc = str_replace('_海报时尚网','',$featureModel->FeatureName);
		
		$ztModel->Channel = 0;
		$ztModel->Title = $featureModel->FeatureName;
		$ztModel->Url = $featureModel->Url;
		$ztModel->Author = $author;
		$ztModel->Keywords = $featureModel->Keywords ? $featureModel->Keywords : '';
		$ztModel->Description = $featureModel->Description;
		$ztModel->EditTag = 0;
		$ztModel->Template = '';
		$ztModel->CreateDate = $featureModel->CreateTime;
		$ztModel->UpdateDate = $featureModel->UpdateTime;
		$ztModel->Tag = $featureModel->ClassId;
		$ztModel->Pic = $picName;
		$ztModel->ListDate = $featureModel->ListTime;
		$ztModel->TagName = $featureModel->CommentTag;
		$ztModel->ZtVideoCate = $featureModel->ColumnId;
		$ztModel->Status = ZtSpecialModel::STATUS_ENABLE;
		$ztModel->PollValid = FeatureUtility::formatTime($featureModel->VoteStartTime).'~'.FeatureUtility::formatTime($featureModel->VoteEndTime);
		$ztModel->CommentDate = FeatureUtility::formatTime($featureModel->CommentStartTime).'~'.FeatureUtility::formatTime($featureModel->CommentEndTime);
		$ztModel->ListDate = $featureModel->ListTime;
		
		$ztLogModel->UserId = $author;
		$ztLogModel->Content = '新建专题';
		$ztLogModel->AddTime = date('Y-m-d H:i:s');
		
		$ztData = new VideoCateData();
		try {
			$ztData->beginTranscation();
			
			$ztData->add($snsModel);
			
			$ztModel->SnsTid = $snsModel->Id;
			$ztData->add($ztModel);
			
			$ztLogModel->ZtsId = $ztModel->Id;
			$ztData->add($ztLogModel);
			
			$id = $ztModel->Id;
			$ztData->endTranscation();
		}
		catch (\Exception $e){
			$ztData->rollback();
			throw $e;
		}
		
		return $id;
	}
	
	public function getVideoCates($filter){
		$videoCateData = new VideoCateData();
		
		return $videoCateData->getAll($filter);
	}
	
	public function updateFeature($id,$arrSet){
		try{
			$this->beginTranscation();
			$this->updateById($id, $arrSet);
			
			if (isset($arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_TAGS])){
				$this->saveFeatureTagRelation($id,$arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_TAGS],true);		
			}
			if (isset($arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_EVENTS])){
				$this->saveFeatureEventRelation($id,$arrSet[FeaturePublishFilter::CONDITION_FIELD_NAME_EVENTS],true);
			}
				
			$this->endTranscation();
		}
		catch (Exception $e){
			$this->rollBack();
			throw $e;
		}
	}
	
	/**
	 * 添加专题
	 * @param \haibao\cms\model\data\FeaturePublish $model
	 */
	public function addFeature($model){
		$this->add($model);
		if ($model->EventIds){
			$this->saveFeatureEventRelation($model->Id,$model->EventIds);
		}
		if ($model->TagIds){
			$this->saveFeatureTagRelation($model->Id,$model->TagIds);
		}
	}
	
	public function saveFeatureEventRelation($featureId,$eventIds,$isEdit = false){
		if ($isEdit){
			$sql = 'delete from FeatureEvent where FeatureId=%s';
			$this->query($sql,array($featureId));
		}
		
		if ($eventIds){	
			$sql = 'insert into FeatureEvent(FeatureId,EventId) values';
			$sqlArr = array();
			$param = array();
			foreach ($eventIds as $eventId){
				array_push($sqlArr,'(%s,%s)');
				array_push($param,$featureId);
				array_push($param,$eventId);
			}
			$sql .= implode(',',$sqlArr);
			$this->query($sql,$param);
		}
	}
	
	public function saveFeatureTagRelation($featureId,$tagIds,$isEdit = false){
		if ($isEdit){
			$sql = 'delete from FeatureTag where FeatureId=%s';
			$this->query($sql,array($featureId));
		}
		
		if ($tagIds){		
			$sql = 'insert into FeatureTag(FeatureId,TagId) values';
			$sqlArr = array();
			$param = array();
			foreach ($tagIds as $tagId){
				array_push($sqlArr,'(%s,%s)');
				array_push($param,$featureId);
				array_push($param,$tagId);
			}
			$sql .= implode(',',$sqlArr);
			$this->query($sql,$param);
		}
	}
	
	public function storeFeatureZip($bytes,$parameters = array()){
		return self::getFeatureMongoBb()->storeFeatureZip($bytes, $parameters);
	}
	
	public function getFeatureZipById($id){
		return self::getFeatureMongoBb()->getFeatureZipById($id);
	}
	
	public function getFeatureZipByIds($ids){
		return self::getFeatureMongoBb()->getFeatureZipByIds($ids);
	}
	
	public function delFeatureZipById($id){
		return self::getFeatureMongoBb()->delFeatureZipById($id);
	}
	
	public function getFeatureImgByIds($ids){
		return self::getFeatureMongoBb()->getFeatureImgByIds($ids);
	}
	
	public function storeFeatureImg($bytes,$parameters = array()){
		return self::getFeatureMongoBb()->storeFeatureImg($bytes, $parameters);
	}
	
	public function delFeatureImgById($id){
		return self::getFeatureMongoBb()->delFeatureImgById($id);
	}
	
	private static function getFeatureMongoBb(){
		if (!self::$mongoDb){
			self::$mongoDb = new FeatureMongo();
		}
		
		return self::$mongoDb;
	}
	
	public function addDataMigrationMap($model,$oldId){
		$this->setConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS);
		$tableName = $model->getTableName();
		$sql = "insert into `DataMigrationMap`(`TableName`,`PrimaryKey`,`OldPrimaryKey`)values(%s,%s,%s)";
		$this->query($sql,array($tableName,$model->Id,$oldId));
	}
	
	public function getDataMigration($model,$newPrimaryKey){
		$this->setConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS);
		$tableName = $model->getTableName();
		$sql  ="select `PrimaryKey`,`OldPrimaryKey` from DataMigrationMap where TableName=%s and PrimaryKey =%s";
		$result = $this->query($sql,array(
				$tableName,$newPrimaryKey
		));
		$oldPrimaryKey = null;
		while ($result->fetch_assoc()){
			$oldPrimaryKey = $result->getData('OldPrimaryKey');
		}
		return $oldPrimaryKey;
	}

	//SISF上海时装周 2017.3.29
	public function addUserVote($openId,$voteCode,$source = 1){
	    $voteCodes = \haibao\www\cache\Message::getSISFOpenVote($openId);
	    /*if($voteCodes && in_array($voteCode,$voteCodes)){
	        return false;
        }*/
        $sql = 'insert into SifsVoteRecord(OpenId,VoteCode,CreateTime,Source) values(%s,%s,%s,%s)';
        $this->query($sql,array($openId,$voteCode,new \DateTime(),$source));

        //需要逻辑调整投票数
        $newEditNum = $editNum = 1;

        $isHav = false;
        $voteNumList = $this->getVoteNumOrder();
        if($voteNumList){
            /*if($voteCode != 41303 && $voteCode != 41003){
                foreach ($voteNumList as $code=>$num){
                    if($code == 41303 || $code == 41003){
                    #if($code == 41303){
                        $num += $editNum;
                        $voteNumList[$code] = $num;
                        $sql = 'update SifsVote set EditVoteNum = EditVoteNum + %s where VoteCode=%s';
                        $this->query($sql,array($editNum,$code));
                    }
                }
                arsort($voteNumList);
            }*/

            foreach ($voteNumList as $code=>$num){
                if($code == $voteCode){
                    $isHav = true;
                    if($code == 41303){
                        $editNum = rand(1,5);
                    }
                    if($code == 41003){
                        $editNum = rand(1,5);
                    }
                    $newEditNum = $num + 1;
                    $num += $editNum;
                    $voteNumList[$code] = $num;
                    break;
                }
            }
            arsort($voteNumList);
        }

        $sql = 'update SifsVote set VoteNum = VoteNum + 1,EditVoteNum = EditVoteNum + %s where VoteCode=%s';
        $this->query($sql,array($editNum,$voteCode));


        if(!$isHav){
            $voteNumList[$voteCode] = $editNum;
            arsort($voteNumList);
        }

        \haibao\www\cache\Message::setVotesNum($editNum);

        \haibao\www\cache\Message::setVoteNumOrder($voteNumList);

        $voteCodes[] = $voteCode;
        \haibao\www\cache\Message::setSISFOpenVote($openId,$voteCodes);

        return $newEditNum;
    }

    public function getVoteNumOrder(){
	    return \haibao\www\cache\Message::getVoteNumOrder();
    }

    public function getVoteCountNum(){
        $num = \haibao\www\cache\Message::getVotesNum();
        if(empty($num)){
            $sql = 'SELECT SUM(EditVoteNum) as Num from SifsVote';
            $result = $this->query($sql)->fetch_assoc();
            if(!empty($result) && isset($result['Num'])){
                $num = (int)$result['Num'];
            }

            \haibao\www\cache\Message::setVotesNum($num);
        }


        return $num;
    }

    public function getVoteList($voteCodes){
        $voteNumList = $this->getVoteNumOrder();
        if(empty($voteNumList)){
            $sql = 'SELECT VoteCode,EditVoteNum from SifsVote';
            $result = $this->query($sql);
            while($result->fetch_assoc()){
                $editNum = (int)$result->getData('EditVoteNum');
                if($editNum < 50){
                    $editNum = $editNum + rand(400,500);
                }
                $sql = 'update SifsVote set EditVoteNum = %s where VoteCode=%s';
                $this->query($sql,array($editNum,$result->getData('VoteCode')));
                $voteNumList[$result->getData('VoteCode')] = $editNum;
            }
            arsort($voteNumList);
            \haibao\www\cache\Message::setVoteNumOrder($voteNumList);
        }

        $resultData = array();
        foreach ($voteCodes as $votecode){
            $order = 0;
            $voteNum = 0;
            if($voteNumList){
                $i = 0;
                foreach ($voteNumList as $code=>$num){
                    $i++;
                    if($votecode == $code){
                        $voteNum = $num;
                        $order = $i;
                        break;
                    }
                }
            }
            if(empty($order)){
                $sql = 'SELECT count(*) as CountNum from SifsVote WHERE EditVoteNum=0';
                $result = $this->query($sql)->fetch_assoc();
                if(!empty($result) && isset($result['CountNum'])){
                    $order = (int)$result['CountNum'];
                }
                $voteNumList[$votecode] = $voteNum;
                arsort($voteNumList);
                \haibao\www\cache\Message::setVoteNumOrder($voteNumList);
            }
            $resultData[$votecode] = array('num'=>$voteNum,'order'=>$order);
        }
        return $resultData;
    }

    public function getUserVoteCode($openId){
        return  \haibao\www\cache\Message::getSISFOpenVote($openId);
    }
}

class VideoCateData extends \haibao\cms\data\BaseMysql{
	public function __construct(){
		$this->setConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE);
	}
}


class FeatureMongo extends \haibao\cms\data\BaseMongoDb{
	const DB_NAME_FEATURE_ZIP = 'featurezip';
	const DB_NAME_FEATURE_IMG = 'featureimg';
	
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\FeaturePublish');
		$this->setConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MONGODB_FEATURE);
	}
	
	public function delFeatureImgById($id){
		$this->removeFileById(self::DB_NAME_FEATURE_IMG, $id);
	}
	
	public function storeFeatureImg($bytes,$parameters){
		return $this->storeBytes(self::DB_NAME_FEATURE_IMG, $bytes, $parameters);
	}
	
	public function getFeatureImgByIds($ids){
		$data = array();
		if ($ids){
			$mongoIds = array();
			foreach ($ids as $id){
				array_push($mongoIds,$this->getMongoId($id));
			}
			
			$cursor = $this->getFiles(self::DB_NAME_FEATURE_IMG,array('_id'=>array('$in'=>$mongoIds)));
			if ($cursor){
				foreach ($cursor as $key=>$value){
					array_push($data,$value);
				}
			}
		}
		
		return $data;
	}
	
	public function getFeatureZipByIds($ids){
		$data = array();
		if ($ids){
			$mongoIds = array();
			foreach ($ids as $id){
				array_push($mongoIds,$this->getMongoId($id));
			}
			
			$cursor = $this->getFiles(self::DB_NAME_FEATURE_ZIP,array('_id'=>array('$in'=>$mongoIds)));
			if ($cursor){
				foreach ($cursor as $key=>$value){
					array_push($data,$value);
				}
			}
		}
		
		return $data;
	}
	
	public function storeFeatureZip($bytes,$parameters){
		return $this->storeBytes(self::DB_NAME_FEATURE_ZIP, $bytes, $parameters);
	}
	
	public function getFeatureZipById($id){
		return $this->getFileById(self::DB_NAME_FEATURE_ZIP, $id);
	}
	
	public function delFeatureZipById($id){
		$this->removeFileById(self::DB_NAME_FEATURE_ZIP, $id);
	}
}